import { useState, useEffect,  } from 'react'
import { useDebounce } from '@uidotdev/usehooks'
import { currentUserCan } from '../lib/utilities'
import * as api from '../lib/data/api'

import { 
  List, 
  ListItem
} from '@material-tailwind/react';
import { StyleTextfield } from '../lib/formstyles';
import { ProjectVulnerability, Vulnerability } from '../lib/data/definitions';

interface VulnerabilityNameInputProps {
  onSelect: (vulnerability: Vulnerability) => void
  value: string
  onChange: (value: string) => void
  isInitialLoad: boolean
  projectId?: number
}

export default function VulnerabilityNameInput(props: VulnerabilityNameInputProps): JSX.Element {
  const [searchValue, setSearchValue] = useState(props.value)
  const [searchComplete, setSearchComplete] = useState(false)
  const debouncedValue = useDebounce<string>(searchValue, 200)
  const [searchResults, setSearchResults] = useState<{ id:number, vulnerabilityname: string }[]>([])
  const [isInitialLoad, setIsInitialLoad] = useState(props.isInitialLoad)
  const loadVulnerabilityTemplate = async(id:number) => {
    const vulnerability = await api.getVulnerability(id.toString()) as Vulnerability;
    return vulnerability;
  }

  const handleSelectedSearchItem = async(vid: number) => {
    
    const vulnerability = await loadVulnerabilityTemplate(vid);
    // in this instance we need to remove the id of the vulnerability to remove the id because we're passing up just the template info, not the vulnerability itself
    const {id, ...vulnerabilityWithoutId} = vulnerability;
    props.onSelect(vulnerabilityWithoutId as Vulnerability)
    setSearchComplete(true)
    setSearchResults([])
  }
  useEffect(() => {
    if(debouncedValue && !searchComplete && !isInitialLoad){
      api.searchVulnerabilities(debouncedValue).then((data) => {
        //filter out the ones that are already in the project
        setSearchResults(data);
      }).catch((error) => {
        console.error(error)
        // toast.error(error.)
      })
    }
  }, [debouncedValue])
  
  // if the value prop changes, it's because the form has been set with new values, so we need to update the input value
  useEffect(() => {
    setSearchValue(props.value)
  }, [props.value])
  useEffect(() => {
    setIsInitialLoad(props.isInitialLoad)
  }, [props.isInitialLoad])
  const handleNameSearch = (event:any) => {
    setSearchValue(event.target.value)
    props.onChange(event.target.value)
    if(event.target.value==''  || event.key === 'Backspace'){
      setIsInitialLoad(false)
      setSearchResults([])
      setSearchComplete(false); // Set searchComplete to false when input is cleared
    }
  }
  return (
            <>
                
                {currentUserCan('Manage Projects') &&
                  <div className="relative max-w-xl">
                    <input 
                      list="searchResults" 
                      value={searchValue} 
                      className={StyleTextfield}
                      type="text" 
                      onChange={handleNameSearch} 
                    />
                    <List
                      className={`max-w-xl absolute bg-white border border-t-0 -mt-0.50 pt-4 border-gray-200 p-0 rounded-b-md z-10 ${searchValue && searchResults.length > 0 ? 'block' : 'hidden'}`}
                      key="searchResults"
                      placeholder="Vulnerability Search Results"
                      onPointerEnterCapture={() => {}}
                      onPointerLeaveCapture={() => {}}
                    >
                        {searchValue && searchResults.map((item) => {
                            return (
                              <div key={`search-${item.id}`}>
                                <ListItem
                                  onClick={() => handleSelectedSearchItem(item?.id)}
                                  placeholder="Vulnerability Search Item"
                                  onPointerEnterCapture={() => {}}
                                  onPointerLeaveCapture={() => {}}
                                >
                                  {item?.vulnerabilityname}
                                </ListItem>
                              </div>
                            );
                          })
                        }
                    </List>
                    
                    
                  </div>
                }
   </>
  )
}